package com.wewins.fota.sys.filter;

import com.alibaba.fastjson.JSON;
import com.wewins.fota.bean.dto.ResponseRst;
import com.wewins.fota.common.constant.AuthConst;
import com.wewins.fota.common.constant.HttpConst;
import com.wewins.fota.sys.token.TokenManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class TokenLogoutHandler implements LogoutHandler {
    private TokenManager tokenManager;

    public TokenLogoutHandler(TokenManager tokenManager) {
        this.tokenManager = tokenManager;
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        String token = request.getHeader(AuthConst.HTTP_HEADER_KEY_AUTHENTICATION);
        if (token != null) {
            tokenManager.removeToken(token);
        }
        response.setStatus(HttpConst.STATUS_OK);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        try {
            JSON.writeJSONString(response.getWriter(), ResponseRst.builder().status(HttpConst.STATUS_OK).data(token).build());
        } catch (IOException e) {
            log.error("System Exception: Can not get response writer:", e);
        }
    }
}
